<template>
  <div>

    <el-button type="primary" size="mini" style="width: 60px;margin-left: 20px;margin-top: 20px" @click="closePage">返回
    </el-button>
    <el-row :gutter="13">
      <p></p>
      <el-form ref="elForm" :rules="rules" :model="formData" size="small" label-width="130px">
        <el-col :span="6">
          <el-form-item label="检查名称:" prop="checkName"
                        :rules="{required: true,message: '请输入检查名称',trigger: 'blur'}">
            <el-input v-model="formData.checkName" placeholder="请输入检查名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="学校名称:" prop="staff">
            <el-checkbox-group v-model="formData.staff" size="medium" @change="schoolChange">
              <el-checkbox v-for="(item, index) in schoolOptions" :key="index" :label="item.value"
                           :disabled="item.disabled">{{ item.label }}
              </el-checkbox>
            </el-checkbox-group>
            <el-form-item prop="schoolsKey" :rules="{required: true,message: '请选择需要检查的学校',trigger:'blur'}">
              <el-transfer ref="transfer" @change="chooseSchool" v-model="formData.schoolsKey" :data="schoolList"
                           :titles="titles"></el-transfer>
            </el-form-item>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="填报日期范围:" prop="dateScope"
                        :rules="{required: true,message: '请选择填报日期',trigger:'blur'}" style="width: 100%">
            <el-date-picker
              v-model="formData.dateScope"
              type="daterange"
              align="center"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item label="问题导入:" prop="fileTag"
                        :rules="{required: true,message: '请导入问题文件',trigger:'blur'}">
            <!-- 用户导入对话框 -->
            <el-upload
              ref="upload"
              :limit="1"
              v-model="formData.fileTag"
              accept=".xlsx, .xls"
              :headers="upload.headers"
              :action="upload.url + '?updateSupport=' + upload.updateSupport"
              :data="formData"
              :disabled="upload.isUploading"
              :on-progress="handleFileUploadProgress"
              :on-success="handleFileSuccess"
              :on-error="handleFileError"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :auto-upload="false"
              drag
              style="width:400px"
            >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip text-center" slot="tip">
                <!--                <div class="el-upload__tip" slot="tip">-->
                <!--                  <el-checkbox v-model="upload.updateSupport"/>-->
                <!--                  是否更新已经存在的问题数据-->
                <!--                </div>-->
                <span>仅允许导入xls、xlsx格式文件。</span>
                <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                         @click="importTemplate">下载模板
                </el-link>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item size="large">
            <el-button type="primary" @click="submitFileForm">提交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>
import {
  listSchool
} from "@/api/patrol/school"
import {
  parseTime
} from "@/utils/ruoyi";
import {
  getToken
} from "@/utils/auth";

import {
  addNotification,
  updateNotification
} from "@/api/patrol/notification";
import {
  importTemplate
} from "@/api/patrol/checkQuestion";

export default {
  props: [],
  data() {

    return {
      pickerTime: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7; //如果没有后面的-8.64e7就是不可以选择今天的;
        }
      },
      titles: ['可选择', '已选择'],
      Authorization: {
        Authorization: getToken()
      },
      notificationId: null,
      formData: {
        //检查名称
        checkName: '',
        //发布时间
        // publishTime: parseTime(new Date(), "{y}-{m}-{d}"),
        //选择的学校类型
        staff: [],
        // 选择的学校
        schoolsKey: [],
        //选择的日期范围
        dateScope: [],
        //文件是否上传
        fileTag: null
      },
      // 问题导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的问题数据
        updateSupport: 0,
        data: {
          cId: 0
        },
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/patrol/checkType/addCheck"
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      rules: {
        /*publishTime: [{
          required: true,
          message: '请选择发布日期'
        }]*/
      },
      schoolOptions: [{
        "label": "幼儿园",
        "value": 0,
        disabled: false
      }, {
        "label": "小学",
        "value": 1,
        disabled: false
      }, {
        "label": "中学",
        "value": 2,
        disabled: false
      }, {
        "label": "高中",
        "value": 3,
        disabled: false
      }, {
        "label": "九年一贯制",
        "value": 4,
        disabled: false
      }, {
        "label": "特殊教育",
        "value": 5,
        disabled: false
      }],

      // 查询学校参数
      querySchoolParams: {
        pageNum: 1,
        name: null,
        type: null,
        nature: null,
        userId: null,
      },
      schoolList: [],
      loading: null
    }
  },
  computed: {},
  watch: {},
  created() {
    this.notificationId = this.$route.query.notifyId;
    listSchool(this.querySchoolParams).then(result => {
      let data = result.rows
      for (let i = 0; i < data.length; i++) {
        this.schoolList.push({
          key: data[i].id,
          label: data[i].name,
          type: data[i].type - 0
        })
      }

      let map = new Map();
      for (const scItem of this.schoolList) {
        map.set(scItem.type, 0)
      }

      for (const scOption of this.schoolOptions) {
        if (map.get(scOption.value) !== 0) {
          scOption.disabled = true
        }
      }

      setTimeout(function () {
        document.getElementsByClassName('el-checkbox-group el-transfer-panel__list').forEach(v => {
          v.getElementsByClassName("el-checkbox__label").forEach(v => {
            v.setAttribute('title', v.textContent)
          })
        })
      }, 500);
    })
  },
  mounted() {
  },
  methods: {
    //选择学校
    chooseSchool() {
      let old = JSON.parse(JSON.stringify(this.schoolList))
      let left = []
      for (let item of old) {
        if (this.formData.schoolsKey.indexOf(item.key) === -1) {
          left.push(item)
        }
      }

      this.formData.staff = []
      for (let item of this.schoolOptions.filter(e => e.disabled === false)) {
        let find = left.find(e => {
          return e.type === item.value
        })
        if (find === undefined) {
          this.formData.staff.push(item.value)
        }
      }
      setTimeout(function () {
        document.getElementsByClassName('el-checkbox-group el-transfer-panel__list').forEach(v => {
          v.getElementsByClassName("el-checkbox__label").forEach(v => {
            v.setAttribute('title', v.textContent)
          })
        })
      }, 500);
    },

    // 修改学校类别把学校加入临时学校list
    schoolChange(vale) {
      this.formData.schoolsKey = []
      for (let item of vale) {
        let filter = this.schoolList.filter(e => {
          return e.type === item
        })
        for (let i = 0; i < filter.length; i++) {
          if (this.formData.schoolsKey.indexOf(filter[i].key) === -1) {
            this.formData.schoolsKey.push(filter[i].key)
          }
        }
      }
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg, "true");
      });
    },
    //文件状态改变
    handleFileChange(file, fileList) {
      this.formData.fileTag = fileList.length
    },
    //文件移除
    handleFileRemove(file, fileList) {
      this.formData.fileTag = null
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      this.resetForm();
      this.loading.close();
      if (response.code === 200) {
        this.$message.success(response.msg);
        this.closePage()
      } else {
        this.$message.error(response.msg);
      }

      // this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
    },
    //文件上传失败处理
    handleFileError() {
      this.loading.close();
    },
    // 提交上传文件
    submitFileForm() {
      console.log(this.formData)
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        this.loading = this.$loading({
          lock: true,
          text: '处理中……',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        this.$refs.upload.submit();
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$refs.upload.clearFiles();
    },
    //关闭页面
    closePage() {
      this.$store.dispatch('tagsView/delView', this.$route)
      this.$tab.openPage("专项检查", "/form/check");
    }
  }
}

</script>
<style scoped>
::v-deep .el-transfer-panel {
  width: 300px;
}

::v-deep.el-transfer :nth-child(3) div {
  border: 1px solid #00B3A8;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header {
  border: 1px solid #00B3A8;
  background: #00B3A8;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label {
  color: white;
}

::v-deep.el-transfer :nth-child(3) .el-transfer-panel__header .el-checkbox__label span {
  color: white;
}

</style>
